package com.kc.sys.controller;

import com.kc.sys.common.ActiverUser;
import com.kc.sys.common.R;
import com.kc.sys.domain.Loginfo;
import com.kc.sys.service.LoginfoService;
import com.kc.sys.util.WebUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author forever_love
 * @create 2019--10--17 9:13
 **/
@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private LoginfoService loginfoService;
    @RequestMapping("login")
    public R login(String loginname,String pwd){

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginname,pwd);
        System.out.println(loginname+"-----------"+pwd);
        System.out.println(token);
        try {
            subject.login(token);
            ActiverUser activerUser = (ActiverUser)subject.getPrincipal();
            WebUtils.getSession().setAttribute("user",activerUser.getUser());
            //记录登录日志
            Loginfo loginfo = new Loginfo();
            loginfo.setLoginname(activerUser.getUser().getName());
            loginfo.setLoginip(WebUtils.getRequest().getRemoteAddr());
            loginfo.setLogintime(new Date());
            loginfoService.save(loginfo);
            return R.ok().message("登录成功。。。");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return R.error().message("用户名或者密码不正确。。。");
        }
    }
}
